package com.llap.exp190929.controller;

import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.entity.Document;
import com.llap.exp190929.entity.User;
import com.llap.exp190929.error.BadRequestException;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.error.UnauthorizedException;
import com.llap.exp190929.security.JwtUser;
import com.llap.exp190929.service.DocumentService;
import com.llap.exp190929.service.UserService;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("documents")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class DocumentsController {
    private DocumentService documentService;
    private UserService userService;

    @GetMapping("")
    public PaginatedDto<Document> findDocuments(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam(required = false, defaultValue = "-1") Integer categoryId) {
        return PaginatedDto.from(documentService.findDocuments(page, pageSize, categoryId));
    }

    @GetMapping("{id}")
    public Document findDocument(@PathVariable Integer id) {
        return documentService.findDocument(id);
    }

    @PostMapping("")
    public Document addDocument(@RequestBody Document document) throws RestException {
        if (document.getTitle() == null || document.getTitle().isEmpty()) throw new BadRequestException("Parameters required");
        JwtUser jwtUser = Util.getLoginUser();
        if (jwtUser == null) throw new UnauthorizedException("");
        User uploader = userService.findUser(jwtUser.getId());
        document.setCreateDate(new Date());
        document.setUploadUser(uploader);
        return documentService.addDocument(document);
    }

    @DeleteMapping("")
    public void deleteDocument(@RequestParam Integer id) throws RestException {
        if (Util.isAdmin(Util.getLoginUser())) documentService.deleteDocument(id);
        else throw new UnauthorizedException("");
    }

    @PatchMapping("")
    public Document updateDocument(@RequestBody Document document) throws RestException {
        if (Util.isAdmin(Util.getLoginUser())) return documentService.updateDocument(document);
        else throw new UnauthorizedException("");
    }
}
